import axios from "axios";
import { getSbData, supabase, supaTabs } from "../base/supabase";
import md5 from "md5";

const { KD100_KEY, KD100_CUSTOMER } = {
  KD100_KEY: "KbSuIQng4180",
  KD100_CUSTOMER: "A3F54578D7B6061C76F0C23A8454989C",
};

const base = new axios.create({
  baseURL: "https://poll.kuaidi100.com",
});

export async function pollDeliver(body, callbackurl) {
  // 订阅推送查询 https://api.kuaidi100.com/document/5f0ffa8f2977d50a94e1023c
  const { company, phone, number, config = {} } = body;
  if (!number) {
    throw "缺少订单号: number";
  }
  if ((company == "shunfeng") & !phone) {
    throw "缺少手机号(顺丰): phone";
  }
  let res = await supabase
    .from(supaTabs.DeliverLog)
    .select()
    .eq("order_no", number);
  let resData = getSbData(res);
  if (resData.length) {
    console.log(11);
    return resData[0];
  }
  delete body.phone;
  delete body.config;
  const parameters = {
    phone,
    callbackurl,
    salt: Date.now() + "",
    resultv2: 1,
    ...config,
  };
  if (!company) {
    if (/^\d/.test(number)) throw "缺少物流公司名称：company";
    parameters.autoCom = 1;
  }
  body.parameters = parameters;
  body.key = KD100_KEY;
  // console.log(body);
  const params = new URLSearchParams();
  params.append("param", JSON.stringify(body));
  const { data } = await base.post("/poll", params);
  if (!data.result) {
    throw data.message;
  }
  res = await supabase
    .from(supaTabs.DeliverLog)
    .insert([
      {
        phone,
        company,
        order_no: number,
      },
    ])
    .select();
  resData = getSbData(res);
  return resData[0];
}

export async function onPollBack(body) {
  const param = JSON.parse(body.param);
  const result = param.lastResult;
  const order_no = result.nu || body.testId;
  if (!order_no) {
    console.log(body);
    return "fail";
  }
  const res = await supabase
    .from(supaTabs.DeliverLog)
    .update({
      result,
      updated_at: new Date(),
      status: result.state * 1, // 默认为0在途，1揽收，2疑难，3签收，4退签，5派件，8清关，14拒签等10个基础物流状态
      //如需要返回高级物流状态，请参考 resultv2 传值
    })
    .eq("order_no", order_no);
  console.log(res);
  return "done";
}

export async function queryDeliver(body) {
  // 实时快递查询 https://api.kuaidi100.com/document/5f0ffb5ebc8da837cbd8aefc
  const { com, phone, num } = body;
  if (!com) {
    throw "缺少快递公司名：com";
  }
  if (!num) {
    throw "缺少订单号: num";
  }
  if ((com == "shunfeng") & !phone) {
    throw "缺少手机号(顺丰): phone";
  }
  if (!body.resultv2) {
    body.resultv2 = 4;
  }
  const param = JSON.stringify(body);
  const signStr = param + KD100_KEY + KD100_CUSTOMER;
  const params = new URLSearchParams();
  params.append("customer", KD100_CUSTOMER);
  params.append("sign", md5(signStr).toUpperCase());
  params.append("param", param);
  const { data } = await base.post("/poll/query.do", params);
  return data;
}
